package framework.service.impl;

import framework.bo.SysRole;
import framework.bo.SysUser;
import framework.bo.SysUserRole;
import framework.dao.ISysUserDao;
import framework.service.SysUserRoleService;
import framework.service.SysUserService;
import framework.util._BeanUtil;
import framework.util.layui._LayuiUtil;
import framework.util.queryFilter.service.impl.IBaseServiceImpl;
import framework.util.queryFilter.service.impl.QueryFilter;
import framework.util.queryFilter.vo.Where;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 吴宇亮 on 2019/2/23 0023 16:21
 */
@Service("SysUserService")
public class SysUserServiceImpl extends IBaseServiceImpl<SysUser, Integer> implements SysUserService {

    @Resource
    private ISysUserDao dao;
    @Resource
    SysUserRoleService sysUserRoleService;

    @Override
    public List<SysUser> list(Map<String, String> requestMap) {
        //根据前端的请求参数，自动生成过滤条件
        QueryFilter.autoFilterByRequestMap(requestMap);
        return dao.list(requestMap);
    }

    @Transactional
    @Override
    public void update(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        SysUser oldBo = this.get(Integer.valueOf(request.getParameter("lid")));
        _BeanUtil.copyPropertiesFromRequest(oldBo, request);
        this.update(oldBo);

        //删除当前用户所有的角色
        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        filter.where(SysUserRole.USER_LID, Where.eq, oldBo.getLid());
        sysUserRoleService.removeByQueryFilter(filter);

        //新增角色
        String rolelid = request.getParameter("rolelid");
        String[] roleArr = rolelid.split(",");
        List<SysUserRole> roleList = new ArrayList<>(roleArr.length);
        for (String roleLid : roleArr) {
            SysUserRole role = new SysUserRole();
            role.setRoleLid(Integer.valueOf(roleLid));
            role.setUserLid(oldBo.getLid());
            roleList.add(role);
        }
        sysUserRoleService.addBatch(roleList);
    }

    @Transactional
    @Override
    public void add(SysUser bo, String[] roleLidArr) {
        this.add(bo);

        List sysUserRoleList = new ArrayList(roleLidArr.length);
        for (String rolelid : roleLidArr) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserLid(bo.getLid());
            sysUserRole.setRoleLid(Integer.valueOf(rolelid));
            sysUserRoleList.add(sysUserRole);
        }
        sysUserRoleService.addBatch(sysUserRoleList);

    }
}
